package com.wisdom.smartbook.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;

import com.wisdom.smartbook.activity.SplashActivity;
import com.wisdom.smartbook.app.MyApp;


/**
 * 异常捕获
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    public static CrashHandler mAppCrashHandler;

    private Thread.UncaughtExceptionHandler mDefaultHandler;

    private MyApp mMyApp;

    public void initCrashHandler(MyApp application) {
        this.mMyApp = application;
        // 获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    public static CrashHandler getInstance() {
        if (mAppCrashHandler == null) {
            mAppCrashHandler = new CrashHandler();
        }
        return mAppCrashHandler;
    }

    @Override
    public void uncaughtException( Thread thread,  Throwable ex) {
        KLog.e("应用崩溃", ex.getLocalizedMessage());
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            ex.printStackTrace();
            restartApp();

        }
    }

    /**
     * 错误处理,收集错误信息 发送错误报告等操作均在此完成.
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                ToastUtils.showShort("很抱歉，程序出现异常，即将重启!");
                Looper.loop();
            }
        }.start();
        return true;  // 使用Toast来显示异常信息
    }


    public void restartApp() {
        Intent intent = new Intent(mMyApp.getBaseContext(), SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP//销毁目标Activity和它之上的所有Activity，重新创建目标Activity。
                | Intent.FLAG_ACTIVITY_CLEAR_TASK//启动Activity时，清除之前已经存在的Activity实例所在的task，这自然也就清除了之前存在的Activity实例！
                | Intent.FLAG_ACTIVITY_NEW_TASK);//很少单独使用，通常与FLAG_ACTIVITY_CLEAR_TASK或FLAG_ACTIVITY_CLEAR_TOP联合使用。
        PendingIntent pendingIntent = PendingIntent.getActivity(
                mMyApp.getBaseContext(), 0, intent, intent.getFlags());
        //Following code will restart your application after 1 seconds
        AlarmManager mgr = (AlarmManager) mMyApp.getBaseContext()
                .getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
                pendingIntent);
        //This will finish your activity manually
        ActivityManagerUtils.getInstance().finishAllActivity();
        //This will stop your application and take out from it.
        System.exit(2);
    }

}
